import { Account, Settings } from "store/Settings";

declare const webView1: any;

let webViewInterval: number | null = null;

function WebViewReady() {
    console.log("webView1 ready " + webView1)

    let injected = false;
    let reportLoading = true;

    function t() {

        console.log("Start t()")

        if (reportLoading) {
            console.log("loadProgress =" + webView1.loadProgress +", " + webView1.loaded )
        }

        if (injected) {
            return
        }

        if (webView1.loaded) {
            reportLoading = false;

            if (!injected) {
                injected = true;

                webView1.runJavaScript(`
                    setTimeout(function(){

                        const doRequest = function(url, body) {
                            return fetch(url, {
                                method: 'POST',
                                headers: {
                                    'Accept': 'application/json',
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify(body)
                            });
                        }
                    
                    
                        const form = document.querySelector("form")
                        const wooper = form.querySelector(".header_feace3");
                    
                        form.innerHTML += '<div style="position: absolute; bottom: 160px;"><input id="input-text" type="text"><button id="send-request">Отправить</button></div>'
                        form.innerHTML += '<div style="position: absolute; bottom: 120px;" id="output"></div>'

                        const sendRequest = document.querySelector("#send-request")
                        const inputText = document.querySelector("#input-text")
                        const output = document.querySelector("#output")
                        output.innerHTML = "Output"
                    
                    
                        try {
                            let stage = 0;
                            let ticket = "";
                    
                            const login = form.querySelector('input[name="email"]')
                            const pass = form.querySelector('input[name="password"]')
                    
                            login.style.background = "brown";
                            pass.style.background = "brown";
                    
                            form.onsubmit = function(e) {
                                e.preventDefault();
                                e.stopPropagation();
                                wooper.innerHTML = "Submit prevented"
                            }
                    
                            form.querySelector('button[type="submit"]').onclick = function(e) {
                                e.preventDefault();
                                e.stopPropagation();
                                wooper.innerHTML = "Button click prevented stage="+ stage
                    
                                if (stage==0) {
                                    doRequest('https://discord.com/api/v9/auth/login', {
                                        login: login.value,
                                        password: pass.value,
                                        undelete:false,
                                        login_source:null,
                                        gift_code_sku_id:null
                                    })
                                    .then((res)=>res.json())
                                    .then((json)=>{
                                        stage = 1;

                                        if (json.mfa) {
                                            ticket = json.ticket
                                            output.innerHTML = JSON.stringify(json, null, "  ")
                                        } else if (json.token) {
                                            output.innerHTML = JSON.stringify(json.token)
                                            inputText.value = json.token
                                            inputText.setAttribute("data-token", json.token)
                                            inputText.select();
                                            inputText.setSelectionRange(0, 99999);
                                            navigator.clipboard.writeText(json.token);

                                            const customEvent = new CustomEvent("framescript:log", {
                                                detail: {
                                                    token: json.token,
                                                }
                                            });
                                            document.dispatchEvent(customEvent);
                                        }
                                    })
                                    .catch(e=>{ wooper.innerText = e.message })
                                }
                            }
                    
                            sendRequest.onclick = function() {
                                if (stage==1) {
                                    doRequest('https://discord.com/api/v9/auth/mfa/totp', {
                                        "code": inputText.value,
                                        "ticket":"<>",
                                        "login_source":null,
                                        "gift_code_sku_id":null
                                    })
                                    .then((res)=>res.json())
                                    .then((json)=>{
                                        stage = 1;
                                        output.innerHTML = JSON.stringify(json, null, "  ")
                    
                                        if (json.token) {
                                            inputText.value = json.token
                                        }
                                    })
                                    .catch(e=>{ wooper.innerText = e.message })
                                }
                            }
                            
                            wooper.innerHTML = "WoopWoop???"
                        } catch(e) {
                            wooper.innerText = e.message
                        }
                    }, 500)

                    let haveFetch = false;

                    if (fetch) {
                        haveFetch = true;
                    }

                    return haveFetch;
                `, function(result: any) {
                    console.log("Document title is", result);
                });
            }
        } else {         
            setTimeout(t, 100)
        }
    }

    t();
}

function WebViewDestroyed() {
    console.log("webView1 destroyed " + webView1 + ", " + webViewInterval)
}